package com.flycent.fanbao.net;

import org.apache.http.Header;
import org.apache.http.HttpStatus;

import com.flycent.fanbao.App;
import com.flycent.fanbao.net.parser.BaseResponseParser;
import com.flycent.fanbao.net.parser.ResponseParser;
import com.loopj.android.http.TextHttpResponseHandler;

/**
 * 服务器响应结果处理器
 * <pre>
 *    // 一个简单的GET请求
 * 	HttpRequestClient.get(context, url, params, new EHResponseHandler&lt;EHBaseResponse<?>>() {

	    public void onParseSuccess(EHBaseResponse<?> result,
		    String responseBody) {
	    }
	    
	});
 * </pre>
 *
 * @param <T> JSON 解析后对应的类型
 *
 * @author Liu.Wenzhu  <lwz0316.gmail.com>
 * @date 2014年7月5日 下午7:56:24 
 *
 */
public abstract class BaseResponseHandler<T>  extends TextHttpResponseHandler implements ResponseHandler<T>{

    public static final String LOG_TAG = "ZJResponseHandler";
    
   @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
       	App.debug(LOG_TAG, "statusCode: " + statusCode
       		+ ", responseString:" + responseString + ", throwable" +( throwable == null? "" : throwable.getMessage()) );
       	App.showShortToast("请求失败");
    }

   @Override
    public void onSuccess(final int statusCode, Header[] headers, final String responseString) {
	   if( statusCode == HttpStatus.SC_OK) {
			try {
				T response = parseResponseString(responseString);
	    		if( response == null ) {
	    			onFailure(HttpStatus.SC_OK, null, "response string is " + responseString, new IllegalArgumentException());
	    		} else {
	    			onParseSuccess(response, responseString);
	    		}
			} catch (final Exception e) {
				e.printStackTrace();
				onFailure(HttpStatus.SC_OK, null, responseString, e.fillInStackTrace());
			    return;
			}
		} else {
		    onFailure(statusCode, headers, responseString, new Throwable("status not 200"));
		}
    }
    
    protected T parseResponseString(final String responseString) throws Exception {
    	App.debug(getRequestURI().toString(), responseString);
		ResponseParser<T> parser = getResponseParser();
		return parser.parse(responseString, BaseResponseParser.getGenericType(getClass()));
    }

    @Override
    public void onParseFailure(String errorCode, String errorMsg) {
    	// no-thing
    }

    @Override
    public void onParseException(Exception e) {
    	onParseFailure("parse-exception", e.getMessage());
    }

    @Override
    public ResponseParser<T> getResponseParser() {
    	return new BaseResponseParser<T>();
    }

}
